package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class AdminLoginTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到了请求，{}", request.getRequestURL().toString());
        // 1.获取请求头中的令牌
        String jwt = request.getHeader(jwtProperties.getAdminTokenName());

        if (!StringUtils.hasLength(jwt)){
            log.info("令牌为空，响应401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        // 3.校验令牌,如果令牌校验失败，则不放行 - 401
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), jwt);
            log.info("解析完令牌,{}",claims);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            // 存入当前登录的id
            BaseContext.setCurrentId(empId);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌非法，响应401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        // 4.放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        BaseContext.removeCurrentId();
    }
}
